//
//  CZComposeViewController.swift
//  Weibo28
//
//  Created by Apple on 16/5/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class CZComposeViewController: UIViewController, UITextViewDelegate {

    //  MARK:   --懒加载控件
    //  右侧按钮
    private lazy var rightButton: UIButton = {
        
        let button = UIButton()
        button.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        button.setTitle("发送", forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        
        //  设置背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        //  设置button文字颜色
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        button.frame.size = CGSize(width: 45, height: 30)
        //  这里指定不起作用,原因是我们的按钮被UIBarButtonItem控制着
//        button.enabled = false
        return button
        
    }()
    //  自定义titleView
    private lazy var titleView: UILabel = {
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 17)
        
        
        if let name = CZUserAccountViewModel.sharedUserAccount.userAccount?.name {
            let title: String = "发微博\n\(name)"
            // 获取name在文本里面的范围
            let range = (title as NSString).rangeOfString(name)
            
            //  创建富文本对象
            let attributedStr = NSMutableAttributedString(string: title)
            //  修改颜色
            attributedStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
            //  修改字体大小
            attributedStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(15), range: range)
            
            label.attributedText = attributedStr
        } else {
            label.text = "发微博"
        }
        
       
        //  多行显示
        label.numberOfLines = 0
        label.textAlignment = .Center
        label.sizeToFit()
        return label
        
    }()
    
    //  定义UITextView
    private lazy var textView: CZComposeTextView = {
        let view = CZComposeTextView()
        //  设置字体大小
        view.font = UIFont.systemFontOfSize(14)
        //  设置代理
        view.delegate = self
        view.placeHolder = "请输入内容"
        //  垂直方向能够滚动
        view.alwaysBounceVertical = true
        return view
    }()
    
    //  toolBar
    private lazy var toolBar: CZComposeToolBar = {
        let view = CZComposeToolBar(frame: CGRectZero)
        return view
    }()
    //  自定义配图
    private lazy var pictureView: CZComposePictureView = {
        let view = CZComposePictureView()
        view.backgroundColor = self.view.backgroundColor
        return view
    }()
   
    //  自定义表情键盘
    private lazy var emoticonKeyboard: CZEmoticonKeyBoard = {
        let view = CZEmoticonKeyBoard()
        //  设置大小
        view.size = CGSize(width: self.textView.width, height: 216)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //  监听键盘改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChageFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //  监听表情按钮点击的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSectedEmoticon:", name: DidSeletedEmoticonNotification, object: nil)
        //  监听删除表情按钮点击的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedDeleteEmoticon", name: DidSelectedDeleteEmoticonButtonNotification, object: nil)
        setupUI()
    }

    private func setupUI() {
        view.backgroundColor = UIColor.whiteColor()
        setupNavUI()
        
        view.addSubview(textView)
        textView.addSubview(pictureView)
        view.addSubview(toolBar)
        //  设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }
        
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(44)
        }
        
       
        
        toolBar.didSeletedButtonClosure = {  [weak self] (type: CZComposeToolBarButtonType) in
            switch type {
            case .Picture:
                print("Picture")
                //  选择图库
                self?.didSelectedPicture()
                
            case .Mention:
                print("Mention")
            case .Trend:
                print("Trend")
            case .Emoticon:
                print("Emoticon")
                //  表情键盘
                self?.didSelectedEmoticon()
            case .Add:
                print("Add")
            }
        }
        //  点击图片按钮回调
        pictureView.didSelectAddImageClosure = { [weak self] in
            self?.didSelectedPicture()
        }
        
    }
    //  设置导航栏视图
    private func setupNavUI() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        //  右侧按钮不可用
        navigationItem.rightBarButtonItem?.enabled = false
        //  自定义titleview
        navigationItem.titleView = titleView
    }
    
    //  MARK:   --点击事件
    @objc private func cancelAction() {
        
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
        
        
    }
    @objc private func sendAction() {
        
//        //  获取表情对应的表情文本附件
//        //  在指定范围内遍历富文本的属性
//        var result = ""
//        textView.attributedText.enumerateAttributesInRange(NSMakeRange(0, textView.attributedText.length), options: []) { (infoDic, range, _) -> Void in
//
//            
//            if let attachment = infoDic["NSAttachment"] as? CZTextAttachment {
//                //  就是文本附件[马上有对象]
//                let chs = attachment.emoticon!.chs!
//                result += chs
//            } else {
//                //  文本
//                
//               let text = self.textView.attributedText.attributedSubstringFromRange(range).string
//                result += text
//                
//            }
//            
//            
//        }
//        print(result)
        
        
        
        
//        //  发送的带有图片的微博
        if pictureView.images.count > 0 {
            upload()
        } else{
            update()
        }
        
    }
    
    //  发送带文字的微博接口
    private func update() {
        //  带有文字的微博
        //   准备参数
        let accesstoken = CZUserAccountViewModel.sharedUserAccount.accessToken!
        let status = textView.emticonText //textView.text!
        
        //  请求发送微博接口
        
        SVProgressHUD.show()
        
        CZNetWorkTools.sharedTools.update(accesstoken, status: status) { (response, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("网络请求异常")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
    
    //  发送带图片的微博请求
    private func upload() {
        //   准备参数
        let accesstoken = CZUserAccountViewModel.sharedUserAccount.accessToken!
        let status = textView.emticonText //textView.text!
        
        SVProgressHUD.show()
        
        //  调用发图片微博接口
        let image = pictureView.images.first!
        
        CZNetWorkTools.sharedTools.upload(accesstoken, status: status, image: image, callBack: { (response, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("网络异常")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
        })
        

    
    }
    
    //  MARK:   -键盘监听事件
    @objc private func keyboardChageFrame(noti: NSNotification) {
        print(noti.userInfo)
        
        let keyboardFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"]! as! NSValue).CGRectValue()
        
        let animationDuration = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]! as! NSNumber).doubleValue
    
        
        
        //  更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - view.frame.size.height)
        }
        
        UIView.animateWithDuration(animationDuration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    //  MARK:   -监听删除表情按钮点击
    @objc private func didSelectedDeleteEmoticon() {
        //  删除textview内容
        textView.deleteBackward()
    }
    
    //  MARK:   -监听表情按钮点击
    @objc private func didSectedEmoticon(noti: NSNotification) {
    
        guard let emoticon = noti.object as? CZEmoticon else {
            return
        }
        //  封装出入表情分文本
        textView.insertEmoticon(emoticon, font: textView.font!)
        
        
        //  一下代码抽取到CZComposeTextView+Extension
//        //  判断点击的表情类型
//        if emoticon.type == "0" {
//
//            
//            //textView.insertText(emoticon.chs!)
//            
//            //  记录上一次的富文本
//            var originalAttr = NSMutableAttributedString(attributedString: textView.attributedText)
//            
//            // 1. 根据表情图片路径名字创建一个UIImage
//            let image = UIImage(named: emoticon.path!)
//            // 2. 根据UIImage对象创建一个NSTextAttachment (文本附件)
//            let attachtment = NSTextAttachment()
//            attachtment.image = image
//            //  取到字体的高度
//            let fontHeight = textView.font!.lineHeight
//            attachtment.bounds = CGRect(x: 0, y: -4, width: fontHeight, height: fontHeight)
//            
//            // 3. 根据NSTextAttachment创建一个NSAttributedString (富文本)
//            let attr = NSAttributedString(attachment: attachtment)
//            
//            //  获取textview的选中范围
//            var range = textView.selectedRange
//            //  替换选中的字符串
//            originalAttr.replaceCharactersInRange(range, withAttributedString: attr)
//            
//            //  追加富文本
//            //originalAttr.appendAttributedString(attr)
//            
//            //  设置富文本的字体大小
//            originalAttr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, originalAttr.length))
//            
//            //  设置富文本
//            textView.attributedText = originalAttr
//            //  每次点击表情开始位置加一
//            range.location += 1
//            //  设置选中范围长度为0
//            range.length = 0
//            
//            //  设置选中范围
//            textView.selectedRange = range
//            
//        } else {
//
//            textView.insertText((emoticon.code! as NSString).emoji())
//        }
        
        
    }
    
    
    
    //  MARK:   - UITextViewDelegate
    func textViewDidChange(textView: UITextView) {
        
//        if textView.hasText() {
//            navigationItem.rightBarButtonItem?.enabled = true
//        } else {
//            navigationItem.rightBarButtonItem?.enabled = false
//        }
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
//        textView.resignFirstResponder()
        self.view.endEditing(true)
    }
    
    deinit {
        //  移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
}

extension CZComposeViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    //  点击表情的操作
    func didSelectedEmoticon() {

        if textView.inputView == nil {
            //  设置表情键盘视图
            textView.inputView = emoticonKeyboard
            //  设置表情按钮icon
            toolBar.showEmoticonIcon(true)
        } else {
            //  设置系统键盘视图
            textView.inputView = nil
            //  设置表情按钮icon
            toolBar.showEmoticonIcon(false)
        }
        //  获取第一响应者
        textView.becomeFirstResponder()
        //  重写加载自定义的intputview
        textView.reloadInputViews()
        
    }
    
    //  点击图片操作
    func didSelectedPicture() {
        let pictureVc = UIImagePickerController()
        
        pictureVc.delegate = self
        
        //  是否支持这种类型
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            pictureVc.sourceType = .Camera
        } else {
            pictureVc.sourceType = .PhotoLibrary
        }
        
        // 判断前置摄像头是否可用
        if UIImagePickerController.isCameraDeviceAvailable(.Front) {
            print("前置摄像头可用")
        } else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
            print("后置摄像头可用")
        } else {
            print("摄像头不可用")
        }
        //  可用编辑
//        pictureVc.allowsEditing = true
        
        presentViewController(pictureVc, animated: true, completion: nil)
        
        
        
    }
    
    //  UIImagePickerControllerDelegate 实现代理方法
    //  实现了代理方法自己调用dismis
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        
        //  获取压缩后的图片
        let scaleImage = image.scaleImageWithWidth(300)
        
//        let data = UIImagePNGRepresentation(scaleImage)
//        data?.writeToFile("/Users/apple/Desktop/2.png", atomically: true)
        
        pictureView.addImage(scaleImage)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //  代码已经抽取到UIImage+Extension
    
//    //  等比压缩图片
//    func scaleImageWithWidth(image: UIImage, scaleWidth: CGFloat) -> UIImage {
//        //  压缩后的宽 100 你要计算压缩后的高度
//        //  比方说图片的大小传入的是 宽度 200 ,高度 300
//        //  计算出压缩后的高度
//        let scaleHeight = scaleWidth / image.size.width * image.size.height
//        
//        
//        let size = CGSize(width: scaleWidth, height: scaleHeight)
//        //  开启上下文
//        UIGraphicsBeginImageContext(size)
//        //  把图片绘制到指定区域
//        image.drawInRect(CGRect(origin: CGPointZero, size: size))
//        //  获取压缩后图片
//        let scaleImage = UIGraphicsGetImageFromCurrentImageContext()
//        
//        //  关闭上下午
//        UIGraphicsEndImageContext()
//        
//        return scaleImage
//    }
    
    
    
    
    
    
    
    
}

